package com.fc.task;

import com.fc.properties.MinioCleanProperties;
import com.fc.utils.MinioUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDate;

@Component//注册Bean
@RequiredArgsConstructor
@Slf4j
public class MinioCleanTask {

    private final MinioUtil minioUtil;
    private final MinioCleanProperties minioCleanProperties;


    @Scheduled(cron = "#{@minioCleanProperties.cron}")
    public void minioClean() {
        try {
            if (!minioCleanProperties.isEnabled()) {
                log.warn("清理【Minio】图片定时任务已关闭");
                return;
            }
            log.info("MinIO 清理任务开始执行...");
            LocalDate cutoff = LocalDate.now().minusDays(minioCleanProperties.getRetainDays());//获取保留自定义天数的时间日期
            log.info("清理截止日期：{}，最早保留日期：{}", cutoff, minioCleanProperties.getEarliestDate());
            int deleteCount = minioUtil.deleteDateFoldersBefore(cutoff);
            log.info("MinIO 清理任务执行完成，共删除 {} 张图片", deleteCount);
        } catch (Exception e) {
            // 防止定时任务因异常停止
            log.error("MinIO 清理任务执行失败", e);
        }
    }
}
